package com.duofan.gmall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.duofan.gmall.cart.feign.ProductFeignService;
import com.duofan.gmall.cart.interceptor.CartInterceptor;
import com.duofan.gmall.cart.service.CartService;
import com.duofan.gmall.cart.to.UserInfoTo;
import com.duofan.gmall.cart.vo.Cart;
import com.duofan.gmall.cart.vo.CartItem;
import com.duofan.gmall.cart.vo.SkuInfoVo;
import com.duofan.gmall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor executor;

    private final static String CART_PREFIX = "gmall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = new CartItem();
        String res = (String) cartOps.get(skuId.toString());
        if(StringUtils.isEmpty(res)) {
            // 购物车中没有该商品
            CompletableFuture<Void> skuInfoFuture = CompletableFuture.runAsync(() -> {
                // 远程查询当前要添加的商品信息
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(skuInfo.getPrice());
            }, executor);

            CompletableFuture<Void> attrValuesFuture = CompletableFuture.runAsync(() -> {
                List<String> attrValues = productFeignService.getSkuSaleAttrValues(skuId);
                // 销售属性组合信息
                cartItem.setSkuAttr(attrValues);
            }, executor);

            CompletableFuture.allOf(skuInfoFuture, attrValuesFuture).get();

            String cartItemJson = JSON.toJSONString(cartItem);
            // key是商品id
            cartOps.put(skuId.toString(), cartItemJson);
            return cartItem;
        } else {
            // 购物车有此商品,只需修改数量
            CartItem item = JSON.parseObject(res, CartItem.class);
            item.setCount(item.getCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(item));
            return item;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(str, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
        List<CartItem> cartItems = getCartItems(tempCartKey);
        if(userInfoTo.getUserId() != null) {
            // 登录状态,如果临时购物车数据还未合并
            if(!CollectionUtils.isEmpty(cartItems)) {
                for (CartItem item : cartItems) {
                    // 合并到用户购物车
                    addToCart(item.getSkuId(), item.getCount());
                }
                // 清空临时购物车
                redisTemplate.delete(tempCartKey);

            }
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            cartItems = getCartItems(cartKey);
        }
        cart.setItems(cartItems);
        return cart;
    }

    @Override
    public void checkItem(Long skuId, Boolean check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check);
        String s = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), s);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), s);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCurrentUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() == null) {
            // 未登录,返回空
            return null;
        } else {
            // 获取所有被选中的购物项
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> cartItemsCheck = cartItems.stream().filter(item -> item.getCheck())
                    .map(item -> {
                        // 获取最新价格
                        BigDecimal price = productFeignService.getPrice(item.getSkuId());
                        item.setPrice(price);
                        return item;
                    })
                    .collect(Collectors.toList());
            return cartItemsCheck;
        }
    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = cartOps.values();
        if(!CollectionUtils.isEmpty(values)) {
            List<CartItem> cartItems = values.stream().map(obj -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return cartItems;
        }
        return null;
    }

    /**
     * 获取要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if(userInfoTo.getUserId() != null) {
            // gmall:cart:1
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }
}
